//
//  UserViewController.m
//  ArtWalker
//
//  Created by Mac Jc on 15/8/3.
//  Copyright (c) 2015年 Mac Jc. All rights reserved.
//

#import "UserViewController.h"
#import "AttentionHomeController.h"
#import "CourseMainController.h"
#import "SetingViewController.h"
#import "ExaminationHomeController.h"
#import "UserLongGestureController.h"
#import "CourseDetailViewController.h"
#import "UserTopView.h"
#import "AllHeader.h"
#import "AttentionTiltleView.h"
#import "UserInfoModel.h"
#import "PayVC.h"
#import "PayAnimationViewController.h"
#import "CollegeDetailViewController.h"
#import "StudioDetailViewController.h"
#import "HomeDetialViewController.h"


//#define kURL @"http://arts1.dlab.com.cn/app/myinfo"
#define kURL @"http://arts1.cn/app/myinfo"

//  创建订单
#define  oderURL @"http://www.arts1.cn/app/order"

@interface UserViewController ()



/**
 *  关注控制器
 */
@property (nonatomic ,strong) AttentionHomeController *attentionHomeVC;

/**
 *  课程控制器
 */
@property (nonatomic ,strong) CourseMainController *courseVC;
/**
 *  考试控制器
 */
@property (nonatomic ,strong) ExaminationHomeController *examinationVC;

@property (nonatomic ,strong) UserLongGestureController *longGestureVC;

// 纪录上一次现实的视图的 UIViewController
@property (nonatomic, strong) UIViewController *lastVC;

/**
 *  头部视图
 */
@property (nonatomic ,strong) UserTopView *topView;

//创建关注头部视图
@property (nonatomic ,strong) AttentionTiltleView *titleView;

//添加好友
@property (nonatomic ,strong) UIButton *VIPButton;
//添加图片
@property (nonatomic ,strong) UIButton *plusButton;
//添加搜索
@property (nonatomic ,strong) UIButton *searchButton;
//添加设置
@property (nonatomic ,strong) UIButton *setButton;

//存储模型数据
@property (nonatomic ,strong) NSMutableArray *dataArray;


// 支付动画
@property (nonatomic, strong) PayAnimationViewController *payAnimationVC;
@property (nonatomic, strong) UIButton *removePayViewButton;
@property (nonatomic, strong) UIButton *payButton;
@property (nonatomic, strong) NSDictionary *oderDic;    //  支付订单字典

@end

@implementation UserViewController

#pragma mark - 懒加载
- (NSMutableArray *)dataArray{
    if (_dataArray == nil)
    {
        self.dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad{
    [super viewDidLoad];
    //创建收藏页面
    [self creactUserCollection];
    //自定义导航栏
    [self navigationControllerVIew];
    //创建头视图
    [self creactTapView];
    //把第一个创建的视图给自己记录的视图
//    _lastVC = _userCollection;
    //设置导航栏的颜色
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.tintColor = kCustomColor(50, 50, 70, 1);
    
    
}

- (void)viewDidAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden = NO;
    
    [self requestData];
}

//请求数据
- (void)requestData
{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    
    manage.responseSerializer.acceptableContentTypes  =[NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"dataForKeyAndUid"];
    
    NSString *uid = dic[@"data"][@"uid"];
    NSString *key = dic[@"data"][@"key"];
    NSDictionary *pardic = nil;
    if (uid && key)
    {
         pardic = @{@"uid":uid,
                    @"key":key};
    }
    
    [manage POST:kURL parameters:pardic
         success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
         // 请求成功的时候调用这个block
         NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
        
        int status = [dic[@"status"] intValue];
        if (status == 1)
        {
            NSDictionary *dict = dic[@"data"];
            
            UserInfoModel *model = [[UserInfoModel alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            [self.dataArray addObject:model];
            
            NSDictionary *nikeface = @{@"nickName":model.nickName,@"userFace":model.userFace};
            
            [[NSUserDefaults standardUserDefaults] setValue:nikeface forKeyPath:@"userFace"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //给头部视图进行传值
                _topView.model = model;
            });
            
            
//            NSLog(@"VIP  info === %@",dict);
            NSLog(@"ISVIP  ========= %@",dict[@"isVIP" ]);
            
            if ([dict[@"isVIP" ] isEqualToString:@"1"]) {
                [_VIPButton setBackgroundImage:[UIImage imageNamed:@"VIPSelect"] forState:UIControlStateNormal];
            }else{
                [_VIPButton setBackgroundImage:[UIImage imageNamed:@"VIPNoraml"] forState:UIControlStateNormal];
            }
        }
    }
    failure:^(AFHTTPRequestOperation *operation, NSError *error)
    {
         // 请求失败的时候调用调用这个block
         NSLog(@"请求失败------%@",error);
    }];
}

/**
 *  创建收藏视图
 */
- (void)creactUserCollection
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 10;
    layout.minimumLineSpacing = 10;
    layout.headerReferenceSize = CGSizeMake(SCREEN_WIDTH, 0.1);
    _userCollection = [[UserCollectionViewController alloc] initWithCollectionViewLayout:layout];
//    [self addChildViewController:_userCollection];
    [_userCollection.collectionView setContentInset:(UIEdgeInsetsMake(4, 0, 54, 0))];
    [self.view addSubview:_userCollection.view];
    
    //调用毛玻璃页面/相册或者相机选择
    __weak UserViewController * wUserCollection = self;
    _userCollection.changeFrameBlock = ^()
    {
        wUserCollection.longGestureVC = [[UserLongGestureController alloc] init];
        wUserCollection.longGestureVC.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        wUserCollection.navigationController.navigationBar.hidden = YES;
        wUserCollection.tabBarController.tabBar.hidden = YES;
        [UIView viewShadowColor:wUserCollection.userCollection.longGestureVC.view];
        [wUserCollection.view addSubview:wUserCollection.longGestureVC.view];
  
    };
    
    //跳转到作品详情页
    _userCollection.pushArtView = ^(MypictureModel *model)
    {
        ArtInfoController *artVC = [[ArtInfoController alloc] initWithStyle:(UITableViewStylePlain)];
        wUserCollection.userCollection.artView.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT + 10);
        wUserCollection.hidesBottomBarWhenPushed = YES;
        [wUserCollection.navigationController pushViewController:artVC animated:YES];
        wUserCollection.hidesBottomBarWhenPushed = NO;
        [wUserCollection.view addSubview:wUserCollection.userCollection.artView.view];
    };
    
    //跳转图片详情页
    _userCollection.pushPhotoView = ^(MyCollectPhotoModel *model)
    {
        HomeDetialViewController *homeDetial = [[HomeDetialViewController alloc] init];
        homeDetial.imageID = model.ImgId;
        
        wUserCollection.hidesBottomBarWhenPushed = YES;
        [wUserCollection.navigationController pushViewController:homeDetial animated:YES];
        wUserCollection.hidesBottomBarWhenPushed = NO;
    };
    
    _userCollection.view.frame = CGRectMake(0, 180, SCREEN_WIDTH, SCREEN_HEIGHT - 180);
    _lastVC = _userCollection;
}

/**
 *  创建关注视图
 */
- (void)creactAttention
{
    _attentionHomeVC = [[AttentionHomeController alloc] init];
    _attentionHomeVC.view.frame = CGRectMake(0, 180, SCREEN_WIDTH, SCREEN_HEIGHT - 180);
    [self.view addSubview:_attentionHomeVC.view];
    
    __weak UserViewController * wUserCollection = self;
    //利用block进行跳转到高校详情页
    _attentionHomeVC.pushSchoolView = ^(AttentionSchoolModel *model)
    {
        CollegeDetailViewController *college = [[CollegeDetailViewController alloc] init];
        college.ID = model.Id;
//        college.navigationController.navigationBar.tintColor = kCustomColor(50, 50, 70, 1);
        college.navigationController.title = model.spaceName;
        college.hidesBottomBarWhenPushed = YES;
        [wUserCollection.navigationController pushViewController:college animated:YES];
        college.hidesBottomBarWhenPushed = NO;
    };
    _attentionHomeVC.pushStudioView = ^(AttentionStudioModel *model)
    {
        StudioDetailViewController *studioVC = [[StudioDetailViewController alloc] init];
        studioVC.space_ID = model.Id;
        studioVC.navigationController.title = model.spaceName;
//        studioVC.navigationController.navigationBar.tintColor = kCustomColor(50, 50, 70, 1);
        studioVC.hidesBottomBarWhenPushed = YES;
        [wUserCollection.navigationController pushViewController:studioVC animated:YES];
        studioVC.hidesBottomBarWhenPushed = NO;
    };
}

/**
 *  创建考试视图
 */
- (void)creactExamination
{
    _examinationVC = [[ExaminationHomeController alloc] init];
    _examinationVC.view.frame = CGRectMake(0, 180, SCREEN_WIDTH, SCREEN_HEIGHT - 180);
    [self.view addSubview:_examinationVC.view];
}
/**
 *  创建课程视图
 */
- (void)creactCourse
{
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 5;
    layout.itemSize = CGSizeMake(SCREEN_WIDTH - 20, 90);
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    _courseVC = [[CourseMainController alloc] initWithCollectionViewLayout:layout];
    [self.view addSubview:_courseVC.view];
    [_courseVC.collectionView setContentInset:(UIEdgeInsetsMake(4, 0, 54, 0))];
    _courseVC.view.frame = CGRectMake(0, 180, SCREEN_WIDTH, SCREEN_HEIGHT - 180);
    
    // 实现 CourseMainCollectionViewController 的block，跳转到详情页面
    __weak UserViewController *wcourseVC = self;
    _courseVC.playcourseblock = ^(CourseModel *model)
    {
        wcourseVC.navigationController.navigationBar.hidden = YES;
        CourseDetailViewController *courseDVC = [[CourseDetailViewController alloc] init];
        courseDVC.model = model;
        courseDVC.hidesBottomBarWhenPushed = YES;
        [wcourseVC.navigationController pushViewController:courseDVC animated:YES];
        courseDVC.hidesBottomBarWhenPushed = NO;
    };
}


/**
 *  创建头部视图
 */
- (void)creactTapView
{

    _topView = [[UserTopView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, 116)];
    [UIView viewWideForShadowColor:_topView];
    _topView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_topView];

     //点击收藏跳到对应的视图
    [self addclickForTitleView:_topView.CollectTitleView SEL:@selector(tapCollect:)];

    //点击收关注到对应的视图
    [self addclickForTitleView:_topView.AttentionTitleView SEL:@selector(tapAttention:)];
   
    //点击收考试到对应的视图
    [self addclickForTitleView:_topView.ExaminationTitleView SEL:@selector(tapExamination:)];

    //点击收课程到对应的视图
    [self addclickForTitleView:_topView.CourseTitleView SEL:@selector(tapCourseTitle:)];
    
}

// 添加点击事件
- (void)addclickForTitleView:(TitleView *)view SEL:(SEL)method
{
    [view.btnNum addTarget:self action:method forControlEvents:UIControlEventTouchUpInside];
    [view.button addTarget:self action:method forControlEvents:UIControlEventTouchUpInside];

}


// 点击后改变被点中的按钮的颜色，其他回复原状
- (void)changeColorOfbutton:(NSInteger)index
{
    for (int i = 1; i < 5; i ++) {
        // 找到数字对应的UIBUtton
        UIButton *numBTN = (UIButton *)[self.view viewWithTag:1050 + i];
        // 找到收藏、关注、考试、课程对应的UIBUtton
        UIButton *nameBTN = (UIButton *)[self.view viewWithTag:1060 + i];
        if (index == 1050 + i || index == 1060 + i)
        {
            [numBTN setTitleColor:kCustomColor(50, 50, 70, 1) forState:(UIControlStateNormal)];
            [nameBTN setTitleColor:kCustomColor(50, 50, 70, 1) forState:(UIControlStateNormal)];
        } else
        {
            [numBTN setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
            [nameBTN setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
        }
    }
}

//点击收藏跳到对应的视图执行的方法
- (void)tapCollect:(UIButton *)tapCollect
{
    NSInteger index = tapCollect.tag;
    [self changeColorOfbutton:index];
    
    
    
    //移除上一个视图
    [_lastVC.view removeFromSuperview];

//    if (_userCollection == nil)
//    {
        //创建要显示的视图
        [self creactUserCollection];
//    }
    
    
    
    [self.view bringSubviewToFront:_userCollection.view];
    [self.view bringSubviewToFront:self.topView];
    //记录当前视图
    _lastVC = _userCollection;
}

//点击关注跳到对应的视图执行的方法
- (void)tapAttention:(UIButton *)tapAttention
{
    NSInteger index = tapAttention.tag;
    [self changeColorOfbutton:index];
    
    //移除上一个视图
    [_lastVC.view removeFromSuperview];

    [self.view bringSubviewToFront:self.topView];
    
//    if (_attentionHomeVC == nil)
//    {
        //创建要显示的视图
        [self creactAttention];
//    }
    
    
    
    [self.view bringSubviewToFront:_attentionHomeVC.view];
//    [UIView viewWideForShadowColor:_attentionHomeVC.titleView];

    
    //记录当前视图
    _lastVC = _attentionHomeVC;
}
//点击考试跳到对应的视图执行的方法
- (void)tapExamination:(UIButton *)tapExamination
{
    NSInteger index = tapExamination.tag;
    [self changeColorOfbutton:index];
    
    //移除上一个视图
    [_lastVC.view removeFromSuperview];
//    if (_examinationVC == nil)
//    {
        //创建要显示的视图
        [self creactExamination];
//    }
    
    [self.view bringSubviewToFront:self.topView];
//    [self.view bringSubviewToFront:_examinationVC.view];
    

    //记录当前视图
    _lastVC = _examinationVC;
}
//点击收课程到对应的视图执行的方法
- (void)tapCourseTitle:(UIButton *)tapCourseTitle
{
    NSInteger index = tapCourseTitle.tag;
    [self changeColorOfbutton:index];
    
    //移除上一个视图
    [_lastVC.view removeFromSuperview];
//    if (_courseVC == nil)
//    {
        //创建要显示的视图
        [self creactCourse];
//    }
    
    [self.view bringSubviewToFront:_courseVC.view];
    [self.view bringSubviewToFront:self.topView];
    
    //记录当前视图
    _lastVC = _courseVC;
}

/**
 *  自定义导航栏
 *
 *  @return 导航栏视图
 */
- (UIView *)navigationControllerVIew
{
    //获取导航栏视图大小
    UIView *navigationView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    self.navigationItem.titleView  = navigationView;

    /**
     *  VIP
     */
    _VIPButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    [_VIPButton setBackgroundImage:[UIImage imageNamed:@"VIPNoraml"] forState:UIControlStateNormal];
    _VIPButton.frame = CGRectMake(5, 12, 22, 24);
    [_VIPButton addTarget:self action:@selector(tapToVIPAnimation:) forControlEvents:(UIControlEventTouchUpInside)];
    [navigationView addSubview:_VIPButton];
    
    /**
     *  设置
     */
    _setButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_setButton setBackgroundImage:[UIImage imageNamed:@"Set"] forState:UIControlStateNormal];
    _setButton.frame = CGRectMake(navigationView.right - 35*(SCREEN_WIDTH/320), 15, 19, 19);
    [_setButton addTarget:self action:@selector(tapSet:) forControlEvents:(UIControlEventTouchUpInside)];
    [navigationView addSubview:_setButton];
    
    /**
     *  搜索
     */
    _searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_searchButton setBackgroundImage:[UIImage imageNamed:@"downloadButton"] forState:UIControlStateNormal];
    _searchButton.frame = CGRectMake(_setButton.right - 70, 14, 21, 21);
    [navigationView addSubview:_searchButton];
    
    /**
     *  添加
     */
    _plusButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_plusButton setBackgroundImage:[UIImage imageNamed:@"Plus"] forState:UIControlStateNormal];
    _plusButton.frame = CGRectMake(_searchButton.right - 70, 15, 17, 17);
    [_plusButton addTarget:self action:@selector(addPhoto:) forControlEvents:(UIControlEventTouchUpInside)];

    [navigationView addSubview:_plusButton];
    
    return navigationView;
}

//  注册会员
- (void)tapToVIPAnimation:(UIButton *)tapSet
{
    //  添加支付动画
    _payAnimationVC = [[PayAnimationViewController alloc] init];
    _payAnimationVC.price = @"199";
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.hidden = YES;
    [self.view addSubview:_payAnimationVC.view];
    
    _payButton = [UIButton buttonWithType:(UIButtonTypeRoundedRect)];
    _payButton.frame = CGRectMake(_payAnimationVC.backgroundView.size.width - 15 - 65 + 25, SCREEN_HEIGHT / 2 - 210 / 2 - 50 + _payAnimationVC.backgroundView.size.height - 17 - 37, 65, 37);;
    _payButton.layer.cornerRadius = 5;
    _payButton.layer.masksToBounds = YES;
    _payButton.alpha = 0;
    _payButton.backgroundColor = kCustomColor(245, 165, 35, 1);
    [_payButton setTitle:@"购买" forState:(UIControlStateNormal)];
    _payButton.titleLabel.font = [UIFont boldSystemFontOfSize:17];
    [_payButton setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [_payButton addTarget:self action:@selector(requistOder) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:_payButton];
    
    [UIView animateWithDuration:0.1 delay:2.3 options:(UIViewAnimationOptionCurveEaseIn) animations:^{
        _payButton.alpha = 1;
    } completion:nil];
    
    _removePayViewButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _removePayViewButton.frame = CGRectMake(SCREEN_WIDTH / 2.0 - 20, SCREEN_HEIGHT - 100 *HEIGHT, 40, 40);
    _removePayViewButton.alpha = 0.3;
    [_removePayViewButton setBackgroundImage:[UIImage imageNamed:@"cancelcon"] forState:(UIControlStateNormal)];
    [_removePayViewButton addTarget:self action:@selector(removePayAnimationView) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:_removePayViewButton];
    
    
}
//进入设置页面
- (void)tapSet:(UIButton *)tapSet
{
    SetingViewController *setingVC = [[SetingViewController alloc] init];
    // setingVC.hidesBottomBarWhenPushed = YES;
    self.tabBarController.tabBar.hidden = YES;
    
    __weak UserViewController *userVC = self;
    setingVC.hidrabBarBlock = ^(){
    userVC.tabBarController.tabBar.hidden = NO;
    };
    [self.navigationController pushViewController:setingVC animated:YES];
   //  setingVC.hidesBottomBarWhenPushed = NO;
}

//添加图片
- (void)addPhoto:(UIButton *)addPhoto
{
    _longGestureVC = [[UserLongGestureController alloc] init];
    _longGestureVC.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    [UIView viewShadowColor:self.userCollection.longGestureVC.view];
    [self.view addSubview:self.longGestureVC.view];

}


/**
 *  创建订单
 */
- (void)requistOder{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    
    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *userDic = [[NSUserDefaults standardUserDefaults] objectForKey:@"dataForKeyAndUid"];
    
    //请求参数
    NSDictionary *pardic = @{@"key":userDic[@"data"][@"key"],@"uid":userDic[@"data"][@"uid"],@"id":@0,@"type":@"vip"};
    //    NSDictionary *pardic = @{@"key":userDic[@"data"][@"key"],@"uid":userDic[@"data"][@"uid"],@"courseId":_model.Id};
    
    [manage POST:oderURL parameters:pardic
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             // 请求成功的时候调用这个block
             NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
             // 请求返回的状态，当status = 1 时有数据
             NSInteger status = [dic[@"status"] integerValue];
             
             NSString *str = nil;
             switch (status) {
                 case 1:{
                     str = @"操作成功";
                     _oderDic = dic;
                     [self tapToPay];
                 }
                     break;
                 case 0:
                     str = @"未知错误";
                     break;
                 case -1:
                     str = @"用户名或密码为空";
                     break;
                 case -2:
                     str = @"用户名或密码错误";
                     break;
                 case -3:
                     str = @"类型不正确";
                     break;
                 case -4:
                     str = @"无法生成订单号";
                     break;
                 case -5:
                     str = @"未找到课程";
                     break;
                 case -6:
                     str = @"不能重复购买";
                     [MBProgressHUD show:@"您已购买，无需重复购买" icon:nil view:self.view];
                     break;
                 default:
                     break;
             }
             
             
             
             NSLog(@" 创建订单  返回数据 ： %@ ",dic);
             
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             // 请求失败的时候调用调用这个block
             NSLog(@"请求失败");
         }];
    
    
}

- (void)tapToPay
{
    PayVC *payVC = [[PayVC alloc] init];
    payVC.navigationController.title = @"在线支付";
    payVC.oderDictionary = _oderDic;
    
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:payVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
    [self removePayAnimationView];
    
    NSLog(@"==== 进入支付页面 ====");
}


//取消当前页面
- (void)removePayAnimationView
{
    [_payAnimationVC.view removeFromSuperview];
    [_payButton removeFromSuperview];
    [_removePayViewButton removeFromSuperview];
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;
}

- (void)tapPlusfriends:(UIBarButtonItem *)plusFriendsButton
{
    
}

@end
